#include "CustomGraphicsRect.h"
#include<QPainter>

QPointF reflectPoint(const QPointF& pointP, const QPointF& pointA, const QPointF& pointB) {
    QPointF vecAB = pointB - pointA;
    QPointF vecAP = pointP - pointA;
    qreal lenAB = QVector2D(vecAB).length();
    QPointF vecAB_unit = vecAB / lenAB;
    qreal projection = QVector2D::dotProduct(QVector2D(vecAP), QVector2D(vecAB_unit));
    QPointF projectedVec = vecAB_unit * projection;
    QPointF reflectedVec = 2 * projectedVec - vecAP;
    QPointF reflectedPoint = pointP + 2 * reflectedVec;
    return reflectedPoint;
}


CustomGraphicsRect::CustomGraphicsRect()

{

    setFlags(QGraphicsItem::ItemIsSelectable );
    setFlag(QGraphicsItem::ItemIsSelectable, true);
//| QGraphicsItem::ItemIsMovable

    _rect<<_points[0]<<_points[1]<<_points[2]<<_points[3];


    init_old_rect(_rect);

//    qDebug()<<_rect;

}

CustomGraphicsRect::~CustomGraphicsRect()
{

}

//矩形统一移动x，y距离
void CustomGraphicsRect::move(float x, float y)
{

    // 修改坐标值
    for (int i = 0; i < _rect.size(); ++i) {
        QPointF &point = _rect[i];
        point.setX(point.x() + x);
        point.setY(point.y() + y);
    }



    scene()->update();
}

void CustomGraphicsRect::setAngle(float val)
{
    _angle = val;
    scene()->update();
}



QPointF CustomGraphicsRect::getBottomright()
{
    qDebug()<<_rect[2];
    return _rect[2];
}

qreal CustomGraphicsRect::getAngle()
{
    return _angle;
}

//移动点，移动角对角
void CustomGraphicsRect::resize(QPointF moveP,QPointF staticP,int indexMove)
{

    qDebug()<<"indexMove:"<<indexMove<<moveP;
    _rect[indexMove] = moveP;
    qreal offset = 5;
//    //在动点在其矩形相邻点附近（offset范围内）-> 将点的位置顺序重新排布/对称
//    if(_rect[(indexMove + 3) % 4].x() - offset  <  moveP.x() && _rect[(indexMove + 3) % 4].x() + offset  >  moveP.x() &&
//       _rect[(indexMove + 3) % 4].y() - offset  <  moveP.y() && _rect[(indexMove + 3) % 4].y() + offset  >  moveP.y())
//    {
//        //在上一个点附近
//        QPolygonF temp = _rect;
//        _rect[0] = temp[3];
//        _rect[1] = temp[2];
//        _rect[2] =
//        _rect[3] =



//    }
//    else if(_rect[(indexMove + 1) % 4].x() - offset  <  moveP.x() && _rect[(indexMove + 1) % 4].x() + offset  >  moveP.x() &&
//            _rect[(indexMove + 1) % 4].y() - offset  <  moveP.y() && _rect[(indexMove + 1) % 4].y() + offset  >  moveP.y())
//    {
//        //在下一个点附近
//        QPolygonF temp = _rect;
//        _rect[0] = temp[1];
//        _rect[1] = temp[0];
//        _rect[2] = temp[3];
//        _rect[3] = temp[2];
//    }

    qreal deltaX = moveP.x() - staticP.x();
    qreal deltaY = moveP.y() - staticP.y();
    qreal angle1 = qAtan2(deltaY, deltaX);//对角线的求倾斜角度

    qDebug()<<"angle1"<<qRadiansToDegrees(angle1); // 将弧度转换为角度

    qreal angle2 = (angle1 - qDegreesToRadians(_angle));//矩形内对角线与长夹角
    qDebug()<<"angle2"<<qRadiansToDegrees(angle2); // 将弧度转换为角度

    qreal distance1 = QLineF(staticP, moveP).length(); //对角线长度
    qreal distance2 = distance1 * qCos(angle2);//矩形长
    qreal distance3 = distance1 * qSin(angle2);//矩形宽
    //对角线：左上--右下
    if(indexMove == 0 || indexMove == 2)
    {
        //对角线：左上--右下
        //_rect[1] = QPointF(_rect[2].x() - qSin(qDegreesToRadians(_angle)) * distance3, _rect[2].y() - qCos(qDegreesToRadians(_angle)) * distance3);
        //_rect[3] = QPointF(_rect[2].x() - qCos(qDegreesToRadians(_angle)) * distance2, _rect[2].y() + qSin(qDegreesToRadians(_angle)) * distance2);


        _rect[1] = QPointF(_rect[0].x() + (qCos(qDegreesToRadians(_angle))) * distance2, _rect[0].y() + (qSin(qDegreesToRadians(_angle))) * distance2);
        _rect[3] = QPointF(_rect[0].x() - (qCos(qDegreesToRadians(90.0 - _angle))) * distance3, _rect[0].y() + (qSin(qDegreesToRadians(90.0 - _angle))) * distance3);

    }
    //对角线：右上--左下
    else if(indexMove == 1 || indexMove == 3)
    {
        //对角线：左上--右下

        //qreal angle3 =qDegreesToRadians(90 - _angle);
        _rect[0] = QPointF(_rect[3].x() + (qCos(qDegreesToRadians(90.0 - _angle))) * distance3, _rect[3].y() - (qSin(qDegreesToRadians(90.0 - _angle))) * distance3);
        _rect[2] = QPointF(_rect[1].x() - (qSin(qDegreesToRadians(_angle))) * distance3, _rect[1].y() + (qCos(qDegreesToRadians(_angle))) * distance3);
    }

     scene()->update();
}

void CustomGraphicsRect::rotate(qreal angle)
{
    //qDebug()<<"旋转前："<<_rect;
    qDebug()<<"旋转："<<angle;
    if(angle < -360 || angle > 360)
    {
        qDebug()<<"!!!";
        return ;
    }
    _angle = angle;

    QPointF center_point((_rect[0].x() + _rect[2].x()) / 2.0,(_rect[0].y() + _rect[2].y()) / 2.0);

    for(int i = 0;i < _rect.size();i++)
    {
        _rect[i] = get_rotate_point(center_point,_rect[i],angle);
    }
    qDebug()<<"旋转后："<<_angle<<_rect;
    //qDebug()<<"旋转："<<_rect;
    scene()->update();
}

QPointF CustomGraphicsRect::get_rotate_point(QPointF center_point, QPointF in_point, qreal angle){
    double dx = center_point.x();
    double dy = center_point.y();
    double x = in_point.x();
    double y = in_point.y();
    double xx,yy;
    //angle = qDegreesToRadians(angle);
    xx = (x-dx)*cos(angle*M_PI/180)-(y-dy)*sin(angle*M_PI/180)+dx;
    yy = (x-dx)*sin(angle*M_PI/180)+(y-dy)*cos(angle*M_PI/180)+dy;

    return QPointF(xx,yy);
}

void CustomGraphicsRect::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setPen(QPen(QColor(255,0,0),2));

    //绘制旋转后的矩形
    painter->drawPolygon(_rect);
    qDebug()<<"paint:"<<_rect;;

}


void CustomGraphicsRect::mousePressEvent(QGraphicsSceneMouseEvent *event)
{


    qDebug()<<"1111111111111111111";
    QPointF cursorPos = event->pos();
    //cursorPos = mapToScene(cursorPos);
    qreal cornerSize = 10;//偏移位置
    //lt_rect
    //rb_rect
    //lb_rect
//    init_old_rect(_rect);
//    qDebug()<<lt_rect_polygon;
//    qDebug()<<rb_rect_polygon;
    qDebug()<<_rect;
    qDebug()<<cursorPos;
//    qDebug()<<lb_rect_polygon;
    //判断鼠标位置
    if((cursorPos.x() <= _rect[0].x() + cornerSize && cursorPos.y() <= _rect[0].y() + cornerSize) &&
        (cursorPos.x() >= _rect[0].x() - cornerSize && cursorPos.y() >= _rect[0].y() - cornerSize))
    {
        //左上角
        qDebug()<<__func__<<"左上角";
        _mouseStatus = DRAGA_LEFTTOP;
    }
    else if((cursorPos.x() <= _rect[1].x() + cornerSize && cursorPos.y() <= _rect[1].y() + cornerSize) &&
             (cursorPos.x() >= _rect[1].x() - cornerSize && cursorPos.y() >= _rect[1].y() - cornerSize))
    {
        //右上角
        qDebug()<<__func__<<"右上角";
        _mouseStatus = DRAGA_RIGHTTOP;
    }
    else if((cursorPos.x() <= _rect[2].x() + cornerSize && cursorPos.y() <= _rect[2].y() + cornerSize) &&
             (cursorPos.x() >= _rect[2].x() - cornerSize && cursorPos.y() >= _rect[2].y() - cornerSize))
    {
        //右下角
        qDebug()<<__func__<<"右下角";
        _mouseStatus = DRAGA_RIGHTBOTTOM;
    }
    else if((cursorPos.x() <= _rect[3].x() + cornerSize && cursorPos.y() <= _rect[3].y() + cornerSize) &&
             (cursorPos.x() >= _rect[3].x() - cornerSize && cursorPos.y() >= _rect[3].y() - cornerSize))
    {
        //左下角
        qDebug()<<__func__<<"左下角";
        _mouseStatus = DRAGA_LEFTBOTTOM;

    }
    else
    {
        qDebug()<<__func__<<"Nothing happened";
        return ;

    }

    //判断鼠标位置
//    if(lt_rect_polygon.boundingRect().contains(cursorPos))
//    {
//        //左上角
//        qDebug()<<__func__<<"左上角";
//        _mouseStatus = DRAGA_LEFTTOP;
//    }
////    else if(rb_rect.boundingRect().contains(cursorPos))
////    {
////        qDebug()<<"右上角";
////        //右上角
////        _mouseStatus = DRAGA_RIGHTTOP;
////    }
//    else if(rb_rect_polygon.boundingRect().contains(cursorPos))
//    {
//        qDebug()<<__func__<<"右下角";
//        //右下角
//        _mouseStatus = DRAGA_RIGHTBOTTOM;
//    }
//    else if(lb_rect_polygon.boundingRect().contains(cursorPos))
//    {
//        qDebug()<<__func__<<"左下角";
//        //左下角
//        _mouseStatus = DRAGA_LEFTBOTTOM;

//    }
//    else if(_rect.boundingRect().contains(cursorPos)){
//        qDebug()<<__func__<<"wwwwwwwww";
//    }
//    else
//    {
//        qDebug()<<__func__<<"Nothing happened";
//        return ;

//    }

    _startPoint = cursorPos;
    QGraphicsItem::mousePressEvent(event);  // 调用基类的函数以确保事件传递

}

void CustomGraphicsRect::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    _mouseStatus = NORMAL;

    QGraphicsItem::mouseReleaseEvent(event);
}

void CustomGraphicsRect::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
//    qDebug()<<__func__;
    QPointF temp = event->pos();
    qDebug()<< "temp" << temp;
    //左键按下
    //if(event->button() == Qt::LeftButton && _mouseStatus != NORMAL)(todo)
    //{
        QPointF cursorPos = event->pos();
        qDebug()<< "cursorPos" << cursorPos;


        QPolygonF tmp = _rect;
        QPointF moveP,staticP;
        int indexMove;
        moveP = cursorPos;
        //判断鼠标位置
        if(_mouseStatus == DRAGA_LEFTTOP)
        {
            //左上角
            qDebug()<<__func__ <<"左上角";
            staticP = _rect[2];
            indexMove = 0;
        }
        else if(_mouseStatus == DRAGA_RIGHTTOP)
        {
            qDebug()<<__func__<<"右上角";
            //右上角
            staticP = _rect[3];
            indexMove = 1;

        }
        else if(_mouseStatus == DRAGA_RIGHTBOTTOM)
        {
            qDebug()<<__func__<<"右下角";
            //右下角
            staticP = _rect[0];
            indexMove = 2;

        }
        else if(_mouseStatus == DRAGA_LEFTBOTTOM)
        {
            qDebug()<<__func__<<"左下角";
            //左下角

            staticP = _rect[1];
            indexMove = 3;
        }

        resize(moveP,staticP,indexMove);
    //}

    QGraphicsItem::mouseMoveEvent(event);
}

void CustomGraphicsRect::init_old_rect(QPolygonF ploy){

    lt_rect_polygon = QRectF(_rect.at(0).x()-5,_rect.at(0).y() - 5,10,10);
    rb_rect_polygon = QRectF(_rect.at(2).x()-5,_rect.at(2).y() - 5,10,10);
    lb_rect_polygon = QRectF(_rect.at(3).x()-5,_rect.at(3).y() - 5,10,10);


    //scene()->update();
}

QRectF CustomGraphicsRect::boundingRect() const{
    QRectF boundingRectF = _rect.boundingRect();
    return QRectF(boundingRectF.x()-10,boundingRectF.y()-10,boundingRectF.width()+20,boundingRectF.height()+20);
}


